package edu.hrbu.redis02.listener;

import edu.hrbu.redis02.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import static edu.hrbu.redis02.constant.RedisConst.GOODS_BAK_POST;
import static edu.hrbu.redis02.constant.RedisConst.GOODS_KEY;

/**
 *
 * 监听redis过期的数据的key
 *
 * @author 徐登宇
 */
@Slf4j
public class KeyExpiredListener extends KeyExpirationEventMessageListener {

    @Autowired
    OrderService orderService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取剩余数量
        String count = stringRedisTemplate.opsForValue().get(message.toString() + ":bak");
        String goodsKey = message.toString();
        // 删除备用数据
        stringRedisTemplate.delete(message.toString() + GOODS_BAK_POST);
        // 将缓存中订单数据写进数据库中
        orderService.rollback(goodsKey.substring(GOODS_KEY.length()), count);
    }
}
